package com.xiaxueqi.auth;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.niagara.security.auth.PermissionDataHandler;
import com.niagara.security.auth.entity.RolePermission;
import com.niagara.security.auth.entity.UserRole;
import com.niagara.service.base.BaseService;
import com.xiaxueqi.entity.security.AppRolePermission;
import com.xiaxueqi.entity.security.AppUserRole;

public class DataHandlerImpl implements PermissionDataHandler {
	protected final Logger logger = LoggerFactory.getLogger(super.getClass());
	private BaseService baseService;
	private static final String SQL_MAP = "select_by_condition";

	@SuppressWarnings("unchecked")
	public <T> List<T> fetchData(Class<T> arg0) throws Exception {
		if (arg0.isAssignableFrom(UserRole.class))
			return (List<T>) this.baseService.getAll(AppUserRole.class);
		if (arg0.isAssignableFrom(RolePermission.class))
			return (List<T>) this.baseService.getAll(AppRolePermission.class);
		return null;
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> fetchData(Class<T> arg0, String arg1) throws Exception {
		try {
			if (arg0.newInstance() instanceof UserRole) {
				AppUserRole userRole = new AppUserRole();
				// userRole.setLoginId(arg1);
				userRole.setUserId(Integer.valueOf(arg1));// 此处修改过
				return (List<T>) this.baseService.find(AppUserRole.class,
						userRole, SQL_MAP);
			}
			if (arg0.newInstance() instanceof RolePermission) {

				AppRolePermission rolePermission = new AppRolePermission();
				rolePermission.setRoleId(new Integer(arg1));
				return (List<T>) this.baseService.find(AppRolePermission.class,
						rolePermission, SQL_MAP);
			}
		} catch (InstantiationException e) {
			this.logger.error(e.getMessage(), e);
			throw e;
		} catch (IllegalAccessException e) {
			this.logger.error(e.getMessage(), e);
			throw e;
		}
		return null;
	}

	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	}
}